package com.qianfeng.zhangwei.easemob.activity;

import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.easemob.chat.EMChatManager;
import com.easemob.exceptions.EaseMobException;
import com.qianfeng.zhangwei.easemob.R;

import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import om.qianfeng.lib.verification.Rule;
import om.qianfeng.lib.verification.Validator;
import om.qianfeng.lib.verification.annotation.ConfirmPassword;
import om.qianfeng.lib.verification.annotation.Password;

@EActivity(R.layout.activity_rigester)
public class RegisterActivity extends BaseActivity implements Validator.ValidationListener {
    @ViewById(R.id.username)
    EditText userNameEditText;
    @ViewById(R.id.password)
    @Password(message = "请输入密码", minLength = 6, order = 1)
    EditText passwordEditText;
    @ViewById(R.id.confirm_password)
    @ConfirmPassword(messageResId = R.string.err, order = 2)
    EditText confirmPwdEditText;
    Validator validator;
    @ViewById(R.id.register_btn)
    Button registerBtn;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    startActivity(new Intent(RegisterActivity.this, MainActivity_.class));
                    RegisterActivity.this.finish();
                    break;
                case 1:
                    //注册出错
                    break;
            }
        }
    };

    @Override
    public void onValidationSucceeded() {
        final String username = userNameEditText.getText().toString().trim();
        final String pwd = passwordEditText.getText().toString().trim();
        ExecutorService service = Executors.newSingleThreadExecutor();
        service.execute(new Runnable() {
            @Override
            public void run() {
                try {
                    EMChatManager.getInstance().createAccountOnServer(username, pwd);
                    handler.sendEmptyMessage(0);
                } catch (EaseMobException e) {
                    e.printStackTrace();
                    handler.sendEmptyMessage(1);
                }
            }
        });
    }

    @Override
    public void onValidationFailed(View failedView, Rule<?> failedRule) {
        if (failedView instanceof EditText) {
            failedView.requestFocus();
        }
    }

    @Click(R.id.register_btn)
    public void onClick(View view) {
        validator = new Validator(this);
        validator.setValidationListener(this);
        validator.validate();
    }
}
